

//
//  NetworkViewModel.m
//  RAC的简单应用
//
//  Created by wsj on 16/8/14.
//  Copyright © 2016年 wsj. All rights reserved.
//

#import "NetworkViewModel.h"
#import "DatesModel.h"
#import "MBProgressHUD+MJ.h"
@interface NetworkViewModel ()

@end
@implementation NetworkViewModel
- (instancetype)init
{
    if (self = [super init]) {
        
        [self initialBind];
    }
    return self;
}
-(void)initialBind
{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
     RACSignal *signal =  [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
         
        NSString *urlString =  [NSString stringWithFormat:@"https://api.douban.com/v2/book/search?q=%@",[@"基础" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
         NSURL *url = [NSURL URLWithString:urlString];
         NSURLRequest *request = [NSURLRequest requestWithURL:url];
         NSURLSession *session = [NSURLSession sharedSession];
         NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//             NSLog(@"111%@ %@",data,error);
             // 发送信号
             [subscriber sendNext:data];
#warning 注意  发送玩信号，必须要掉完成发送，不然一直持续发送
             // 发送完成
             [subscriber sendCompleted];
         }];
         [dataTask resume];
         return nil;
     }];
        // 返回信号时候，将信号的数据转化为模型数组
        return [signal map:^id(NSData *data) {
            
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *data_array = dict[@"books"];
            // 字典转模型也可以简单写法
            //            NSMutableArray *models_array_M = [NSMutableArray array];
            //            [data_array.rac_sequence.signal subscribeNext:^(id x) {
            //                [models_array_M addObject:[DatesModel modelWithDict:x]];
            //            }];
#warning 字典转模型高级写法
            NSArray *models_array = [[data_array.rac_sequence map:^id(id value) {
                return [DatesModel modelWithDict:value];
            }] array];

            return models_array;
        }];
        
    }];
    // 监听状态
    [[self.command.executing skip:1]subscribeNext:^(id x) {
        if ([x isEqualToNumber:@(YES)]) {// 为啥是isEqualToNumberis，我真的不知道
            [MBProgressHUD showMessage:@"网络加载中....."];
        }else{
            [MBProgressHUD hideHUD];
        }
    }];
    // 订阅信号
    [self.command.executionSignals.switchToLatest subscribeNext:^(NSArray *x) {
        if (x.count != 0) {
            self.models = x;
            [self.tableView reloadData];
        }
    }];

}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    DatesModel *book = self.models[indexPath.row];
    cell.detailTextLabel.text = book.subtitle;
    cell.textLabel.text = book.title;
    return cell;
}
@end
